package com.geeklei.media.ui.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Movie;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.geeklei.media.ui.R;

import java.io.InputStream;

public class GifView extends android.support.v7.widget.AppCompatImageView {
    private int mImageHeight;
    private int mImageWidth;
    private Movie mMovie;
    private long mMovieStart;

    public GifView(Context context) {
        super(context);
    }

    public GifView(Context context, AttributeSet attributeSet) {
        this(context, attributeSet, 0);
    }

    public GifView(Context context, AttributeSet attributeSet, int i) {
        super(context, attributeSet, i);
        InputStream openRawResource = getResources().openRawResource(R.raw.vp_loading_gif);
        this.mMovie = Movie.decodeStream(openRawResource);
        if (this.mMovie != null) {
            Bitmap decodeStream = BitmapFactory.decodeStream(openRawResource);
            this.mImageWidth = decodeStream.getWidth();
            this.mImageHeight = decodeStream.getHeight();
            decodeStream.recycle();
            invalidate();
        }
    }

    protected void onDraw(Canvas canvas) {
        if (this.mMovie == null) {
            super.onDraw(canvas);
            return;
        }
        playMovie(canvas);
        invalidate();
    }

    protected void onMeasure(int i, int i2) {
        super.onMeasure(i, i2);
        if (this.mMovie != null) {
            setMeasuredDimension(this.mImageWidth, this.mImageHeight);
        }
    }

    private boolean playMovie(Canvas canvas) {
        long uptimeMillis = SystemClock.uptimeMillis();
        if (this.mMovieStart == 0) {
            this.mMovieStart = uptimeMillis;
        }
        int duration = this.mMovie.duration();
        if (duration == 0) {
            duration = 100;
        }
        this.mMovie.setTime((int) ((uptimeMillis - this.mMovieStart) % ((long) duration)));
        this.mMovie.draw(canvas, 0.0f, 0.0f);
        if (uptimeMillis - this.mMovieStart < ((long) duration)) {
            return false;
        }
        this.mMovieStart = 0;
        return true;
    }
}
